/*
 * @Descripttion: 导出文件的混入文件
 * @Author: caijj
 * @Date: 2020-12-28 11:25:32
 * @LastEditors: caijj
 * @LastEditTime: 2021-03-18 15:12:26
 */
import { exportReport, getReportDownloadUrl } from '@/api/commonApi';
import { saveAs } from 'file-saver';
export default {
  data() {
    return {
      exporting: false,
      timer: null
    };
  },
  beforeDestory() {
    this.timer = null;
  },
  methods: {
    onExportReport(type, val) {
      const api = [].slice.call(arguments, -1)[0];
      const params = { ...this.formData, ...val };
      this.exporting = true;
      if (api && typeof api === 'function') {
        this.otherDownload(api, params, type);
        return;
      }
      exportReport(type, params)
        .then(({ data: fileName }) => {
          this.onLoopFetchFileUrl(type, fileName);
        })
        .catch(err => {
          this.$message.error(err);
          this.exporting = false;
        });
    },
    onLoopFetchFileUrl: async function(type, fileName) {
      try {
        // 请求下载链接
        const res = await getReportDownloadUrl(type, { fileName });
        const { resultCode, data } = res || {};
        if (resultCode === '0000' && data) {
          this.exporting = false;
          // 如果返回数据包含error
          if (data === 'error') {
            this.$message.error('报表文件下载失败, 请您稍后再试！');
            return this.onClearTimeout();
          }
          this.$message.success('报表文件已生完毕, 开始下载。');
          const link = document.createElement('a');
          link.href = data;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          return this.onClearTimeout();
        }
        this.timer = setTimeout(
          () => this.onLoopFetchFileUrl(type, fileName),
          3000
        );
      } catch (err) {
        console.log('onLoopFetchFileUrl_method_err:', err);
        this.fileUrl = '';
        this.exporting = false;
      }
    },
    onClearTimeout() {
      if (this.timer) clearTimeout(this.timer);
    },
    otherDownload(api, params, name) {
      try {
        params.export = params.downType ? 2 : 1;
        const suffix = params.downType ? '.csv' : '.xlsx';
        api(params).then(blob => {
          this.exporting = false;
          saveAs(blob, name + Date.now() + suffix);
        }, () => {
          this.exporting = false;
        });
      } catch (e) {
        throw TypeError(`this ${api} is must be Promise or return Promise function`);
      }
    }
  }
};
